package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"recruit-ease/cache"
	"recruit-ease/model"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))

	offset := (page - 1) * size

	var count int64
	model.DB.Model(&model.Work{}).Count(&count)

	var work []model.Work
	model.DB.Offset(offset).Limit(size)

	redis_key := "work_list"
	jsonData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if jsonData == "" {
		model.DB.Find(&work)
		cacheData, _ := json.Marshal(work)
		cache.Rdb.Set(cache.Ctx, redis_key, cacheData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(jsonData), &work)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"work":  work,
		},
	})
	return

}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var work model.Work
	model.DB.Where("id = ?", id).First(&work)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": work,
	})
	return
}
